package cn.hnucm.orderservice.config;

import cn.hnucm.orderservice.entity.TbLog;
import cn.hnucm.orderservice.service.TbLogService;
import cn.hnucm.orderservice.utils.IPUtils;
import cn.hnucm.orderservice.utils.MyLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 系统日志：切面处理类
 */
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private TbLogService tbLogService;
    private long startTime;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation( cn.hnucm.orderservice.utils.MyLog)")
    public void logPoinCut() {
    }

    @Before("logPoinCut()")
    public void doBefore(){
        //设置方法开始的时间
        this.startTime = System.currentTimeMillis();
    }

    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) throws JSONException {
        System.out.println("切面。。。。。");
        //保存日志
        TbLog log = new TbLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (myLog != null) {
            String value = myLog.value();
            log.setOperation(value);        //保存获取的操作
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        log.setMethod(className + "." + methodName);

        //请求的参数类型
        Parameter[] parameters = method.getParameters();
        //获取请求的参数值
        Object[] args = joinPoint.getArgs();
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < parameters.length; i++) {
            jsonObject.put(parameters[i].getName(),args[i].toString());
        }
        //将参数所在的数组转换成json并保存
        log.setParams(jsonObject.toString());

        //设置保存的时间的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //保存时间
        log.setCreatetime(sdf.format(new Date()));



        //获取用户ip地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        log.setIp(IPUtils.getIpAddr(request));

        //获取用户名
        String userId = request.getHeader("userId");
        if (userId != null) log.setUserId(Integer.valueOf(userId));
        else log.setUserId(new Integer(0));
        // 获取并设置方法执行时间
        log.setTime(System.currentTimeMillis() - startTime);

        //调用service保存SysLog实体类到数据库
        tbLogService.addLog(log);
    }

}